package com.bw.lib_core.bus;

import androidx.annotation.NonNull;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.Observer;

import java.util.concurrent.atomic.AtomicBoolean;

/**
 * LiveData数据倒灌：数据发送后，页面才订阅，收到了之前的数据
 */
public class BusLiveData<T> extends MutableLiveData<T> {

    //原子性Boolean; 保证多线程操作
    private AtomicBoolean flag = new AtomicBoolean();

    @Override
    public void observe(@NonNull LifecycleOwner owner, @NonNull Observer<? super T> observer) {
        super.observe(owner, new Observer<T>() {
            @Override
            public void onChanged(T t) {
                //compareAndSet(true, false) 参数：目标值，更新值；如果原有值和目标值相同更新值
                if (flag.compareAndSet(true, false)) {
                    observer.onChanged(t);
                }
            }
        });

    }

    @Override
    public void setValue(T value) {
        flag.set(true);
        super.setValue(value);
    }
}
